//
//  HomeViewController.m
//  BabyBedtimeStory
//
//  Created by qianfeng on 15-6-19.
//  Copyright (c) 2015年 张鹏毅. All rights reserved.
//

#import "HomeViewController.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "JHRefresh.h"
#import "StoryModel.h"
#import "HomeCell.h"
#import "LZXHelper.h"
#import "DetailViewController.h"

#define kScreenSize [UIScreen mainScreen].bounds.size

@interface HomeViewController () <UITableViewDataSource,UITableViewDelegate>
{
    AFHTTPRequestOperationManager *_manager;
}
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataArr;
@property (nonatomic,strong) NSMutableArray *HeaderArr;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"宝宝睡前故事";
    self.isRefreshing = NO;
    [self creatTableView];
    [self creatAf];
    [self StartDownloadingData];
    [self beginRefreshing];
}

#pragma mark - 创建tableView
-(void)creatTableView{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kScreenSize.width, kScreenSize.height-64-49)];
    self.dataArr = [[NSMutableArray alloc]init];
    self.tableView.dataSource = self;
    self.tableView.delegate =self;
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeCell" bundle:nil] forCellReuseIdentifier:@"HomeCell"];
    [self.view addSubview:self.tableView];
    self.HeaderArr = [[NSMutableArray alloc]init];
}

#pragma mark - 创建下载
-(void)creatAf{
    _manager = [AFHTTPRequestOperationManager manager];
    _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
}

#pragma mark - 开始下载数据
-(void)StartDownloadingData{
    __weak typeof(self) weakSelf = self;
    BOOL isExist = [[NSFileManager defaultManager]fileExistsAtPath:[LZXHelper getFullPathWithMyCacheFile:kHome]];
    BOOL isTimeOut = [LZXHelper isTimeOutFile:kHome time:24*60*60];
    if (self.isRefreshing == NO&&isExist == YES&&isTimeOut == NO) {
        NSData *data = [NSData dataWithContentsOfFile:[LZXHelper getFullPathWithMyCacheFile:kHome]];
        [self ParsingWithData:data];
    }else{
    self.isRefreshing = YES;
    [_manager GET:kHome parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            NSData *data = (NSData *)responseObject;
            NSString *filePath = [LZXHelper getFullPathWithMyCacheFile:kHome];
            [data writeToFile:filePath atomically:YES];
            [weakSelf ParsingWithData:data];
        }
        [weakSelf stopRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [weakSelf stopRefreshing];
    }];
    }
}

#pragma mark - 数据解析
-(void)ParsingWithData:(NSData *)data{
    [self.dataArr removeAllObjects];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    NSDictionary *HeaderDict = dict[@"data"][@"danxinben"];
    NSDictionary *PageDict = dict[@"data"][@"page"];
    NSArray *arrDict = dict[@"data"][@"data_list"];
    
    StoryModel *model = [[StoryModel alloc]init];
    model.image_url = HeaderDict[@"image_url"];
    model.describe = HeaderDict[@"describe"];
    model.page_size = PageDict[@"page_size"];
    [self.HeaderArr addObject:model];
    [self creatHeaderView];
    
    for (NSDictionary *dictArr in arrDict) {
        StoryModel *model = [[StoryModel alloc]init];
        [model setValuesForKeysWithDictionary:dictArr];
        [self.dataArr addObject:model];
    }
    [self.tableView reloadData];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HomeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeCell" forIndexPath:indexPath];
    StoryModel *model = self.dataArr[indexPath.row];
    [cell showWithModel:model];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

#pragma mark  - 头视图标题
-(void)creatHeaderView{
    StoryModel *model = [[StoryModel alloc]init];
    model = self.HeaderArr.lastObject;
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenSize.width, 200)];
    [imageView sd_setImageWithURL:[NSURL URLWithString:model.image_url] placeholderImage:[UIImage imageNamed:@"yujiazai"]];
    self.tableView.tableHeaderView = imageView;
}

#pragma mark - 选中cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DetailViewController *vc = [[DetailViewController alloc]init];
    StoryModel *model = self.dataArr[indexPath.row];
    vc.id = model.id;
    vc.title = model.title;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)beginRefreshing{
    __weak typeof(self) weakSelf = self;
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSelf.isRefreshing) {
            return ;
        }
        weakSelf.isRefreshing = YES;
        [weakSelf StartDownloadingData];
    }];
}

-(void)stopRefreshing{
    if (self.isRefreshing) {
        self.isRefreshing = NO;
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultSuccess];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
